package com.example.app2;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app2.pojo.GoodsInfo;

public class ShoppingDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private ShoppingDBHelper mDBHelper;
    private TextView tv_title;
    private TextView tv_count;
    private TextView tv_goods_price;
    private TextView tv_goods_desc;
    private ImageView iv_goood_pic;
    private int goodsId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_detail);
        tv_title = findViewById(R.id.tv_title);
        tv_count = findViewById(R.id.tv_count);
        tv_goods_price = findViewById(R.id.tv_goods_price);
        tv_goods_desc = findViewById(R.id.tv_goods_desc);
        iv_goood_pic = findViewById(R.id.iv_goods_pic);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_cart).setOnClickListener(this);
        findViewById(R.id.btn_add_cart).setOnClickListener(this);

        tv_count.setText(String.valueOf(MyApplication.getInstance().goodsCount));
        mDBHelper = ShoppingDBHelper.getInstance(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        showDetail();
    }

    private void showDetail() {
        goodsId = getIntent().getIntExtra("goodsId",-1);
        if(goodsId ==-1)
        {
            Log.d("tang", "showDetail: 查询失败");
            return;
        }
        GoodsInfo info = mDBHelper.queryGoodsInfoById(goodsId);
        tv_title.setText(info.name);
        tv_goods_desc.setText(info.description);
        tv_goods_price.setText(String.valueOf(info.price));
        iv_goood_pic.setImageURI(Uri.parse(info.picPath));

    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_cart:
                Intent intent = new Intent(ShoppingDetailActivity.this, ShoppingCartActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_add_cart:
                addToCart(goodsId);
                break;
        }
    }

    private void addToCart(int goodsId) {
        mDBHelper.insertCartInfo(goodsId);
        int count=++MyApplication.getInstance().goodsCount;
        tv_count.setText(String.valueOf(count));
        Toast.makeText(this, "已添加到购物车", Toast.LENGTH_SHORT).show();
    }

}
